<template>
  <tr>
    <td>{{ index + 1 }}</td>
    <td>{{ book.name }}</td>
    <td>{{ book.date }}</td>
    <td>{{ showPrice(book.price) }}</td>
    <td>
      <button @click="decrement(index)" :disabled="book.count <= 1">-</button>
      {{ book.count }}
      <button @click="increment(index)">+</button>
    </td>
    <td><button @click="remove(index)">移除</button></td>
  </tr>
</template>

<script lang="ts" setup>
import { inject, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, onUpdated } from "vue";
defineProps({
  book: {
    type: Object,
    required: true,
  },
  index: {
    type: Number,
    required: true,
  },
});

// const emit = defineEmits(['increment', 'decrement', 'remove']);

// const increment = () => {
//   emit('increment', props.index);
// };

// const decrement = () => {
//   emit('decrement', props.index);
// };

// const remove = () => {
//   emit('remove', props.index);
// };

const showPrice = (price: number) => {
  return "￥" + price.toFixed(2);
};

// 子组件现在可以直接使用祖组件传递的方法
const increment = inject("increment") as (index: number) => void;
const decrement = inject("decrement") as (index: number) => void;
const remove = inject("remove") as (index: number) => void;

/* 组件的生命周期 */
onBeforeMount(() => {
  console.log('子组件的onBeforeMount --- 子组件挂载前')
})
onMounted(()=> {
  console.log('子组件的onMounted --- 子组件挂载')
})
onBeforeUnmount(() => {
  console.log('子组件onBeforeUnmount  --- 子组件卸载前')
})
onUnmounted(() => {
  console.log('子组件的onUnmounted  --- 子组件卸载')
})
onBeforeUpdate(() => {
  console.log('子组件的onBeforeUpdate --- 子组件数据更新前')
})
onUpdated(() => {
  console.log('子组件的onUpdate --- 子组件数据更新')
})


</script>
